package com.seek.inter;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.dto.ResultInfo;
import com.seek.service.InterService;
import com.seek.util.CommonUtil;
import com.seek.util.JsonUtil;

public class UpdateInter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private InterService interService = (InterService)SpringContextHolder.getBean("interService");
	
	/**
	 * 检测客户端是否需要更新
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ResultInfo checkUpdate(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		String cVersion = reqJson.getString("v"); //版本
		String name = reqJson.getString("name");  //应用名
		String os = reqJson.getString("os");      //操作系统
		try{		
			// 从缓存中获取最新版本信息
			Map<String,Object> cached = JsonUtil.fromJson(CacheUtil.getRedisData("CHECK_UPDATE_"+name+"_"+os+"_"+cVersion));
			if (cached == null || cached.keySet().size() < 1){
				// 从数据库中取得版本升级所数据
				String sql = "select a.app_version appVersion, (case when STRCMP(a.app_version,?)<1 then 0 when STRCMP(a.app_version,?)=1 and must_flag=0 then 1 else 2 end) needUpdate,a.issure_note updateNote,a.issure_url updateUrl from t_version a where a.app_name=? and a.app_os=?";
				cached = interService.findOneMapBySql(sql, new Object[]{cVersion,cVersion,name,os});
				if (cached == null || cached.size()<1){
					cached.put("needUpdate", 0);
				}
				CacheUtil.putRedisData("CHECK_UPDATE_"+name+"_"+os+"_"+cVersion, JsonUtil.toJson(cached));
				// 取得版本所有的key，并添加上这个key
				String keys = CacheUtil.getRedisData("UPDATE_VERSION_KEYS");
				if (CommonUtil.isEmpty(keys)){
					keys = "CHECK_UPDATE_"+name+"_"+os+"_"+cVersion;
				}else{
					if (keys.indexOf("CHECK_UPDATE_"+name+"_"+os+"_"+cVersion) < 0){
						keys = keys + ","+ "CHECK_UPDATE_"+name+"_"+os+"_"+cVersion;
					}
				}
				CacheUtil.putRedisData("UPDATE_VERSION_KEYS", keys);
			}
			
			result.setStatus(0);
			result.setMessage("成功");
			result.setBody(cached);
			
			return result;
		}catch(Exception e){
			logger.error("系统异常",e);
			result.setStatus(1);
			result.setMessage(e.getMessage());
			return result;
		}
	}
}
